package com.juyu.miliao.api.controller;

import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.GiftSpend;
import com.juyu.miliao.api.domain.UserAuthenticationInfo;
import com.juyu.miliao.api.domain.dto.DynamicGiftInfoDTO;
import com.juyu.miliao.api.domain.dto.DynamicInfoDTO;
import com.juyu.miliao.api.domain.dto.DynamicReportInfoDTO;
import com.juyu.miliao.api.domain.dto.WhitePacketDynamicInfoDTO;
import com.juyu.miliao.api.domain.vo.DynamicDetailInfoVo;
import com.juyu.miliao.api.domain.vo.DynamicInfoVo;
import com.juyu.miliao.api.domain.vo.WhitePacketDynamicDetailInfoVo;
import com.juyu.miliao.api.domain.vo.WhitePacketDynamicInfoVo;
import com.juyu.miliao.api.service.*;
import com.juyu.miliao.api.service.whitepacket.WhitePacketDynamicInfoService;
import com.juyu.miliao.api.validator.GiftSpendCheck;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.OpenApiStatus;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.VerifyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 社区动态信息controller
 *
 * @author xuanqicheng
 * @create 2019-21-09:43
 */
@RestController
@RequestMapping("/dynamic")
@CrossOrigin
public class DynamicInfoController {

    public static final String APP_KEY = "APP_AUDIT";

    @Autowired
    private DynamicInfoService dynamicInfoService;

    @Autowired
    private WhitePacketDynamicInfoService whitePacketDynamicInfoService;

    @Autowired
    private GiftSpendService giftSpendService;

    @Autowired
    private OpenApiService openApiService;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;

    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private UserAuthenticationInfoService userAuthenticationInfoService;



    /**
     * 发布动态
     * @param token
     * @param dynamicInfoDTO
     * @param bindingResult
     */
    @PostMapping("/")
    public void addDynamicInfo(HttpServletRequest request, Authentication token, @Validated DynamicInfoDTO dynamicInfoDTO,
                               BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            throw  new ConsumeRuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }

        Boolean isAudit = getAudit(request);

        Subject subject = (Subject) token.getPrincipal();

        if(!isAudit){

            dynamicInfoDTO.setUserId(subject.getId());

            UserCacheVo userCacheVo = userInfoCache.getUserCacheInfo(subject.getId());

            if(userCacheVo.getSex() == 2 && userCacheVo.getIsHost()!=1){
                throw new ConsumeRuntimeException("4001","非主播用户请认证", HttpStatus.BAD_REQUEST);

            }
            dynamicInfoDTO.setIsHost(userCacheVo.getIsHost());
            dynamicInfoDTO.setSex(userCacheVo.getSex());
            dynamicInfoService.addDynamciInfo(dynamicInfoDTO);

        }else{

            WhitePacketDynamicInfoDTO whitePacketDynamicInfoDTO = new WhitePacketDynamicInfoDTO();

            BeanUtils.copyProperties(dynamicInfoDTO,whitePacketDynamicInfoDTO);

            whitePacketDynamicInfoDTO.setAppKey(APP_KEY);

            whitePacketDynamicInfoDTO.setUserId(subject.getId());

            whitePacketDynamicInfoService.addDynamciInfo(whitePacketDynamicInfoDTO);
        }

    }


    @PostMapping("/delete")
    public void deleteDynamicInfo(HttpServletRequest request,long dynamicId){
        Boolean isAudit = getAudit(request);
        if(!isAudit){
            dynamicInfoService.deleteDynamicInfo(dynamicId);
        }else{
            whitePacketDynamicInfoService.deleteDynamicInfo(dynamicId);

        }

    }

    @GetMapping("/{page}-{pageSize}")
    public Object getDynamicInfoList(HttpServletRequest request,Authentication token,
                                                  @PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize) {

        if (page <= 0) {
            page = 1;
        }
        if (pageSize <= 0) {
            pageSize = 20;
        }

        Subject subject = (Subject) token.getPrincipal();
        Boolean isAudit = getAudit(request);
        if(!isAudit) {
            List<DynamicInfoVo> list = dynamicInfoService.getDynamicInfoList(subject.getId(), page, pageSize);
            return list;
        }else{
            List<WhitePacketDynamicInfoVo> list = whitePacketDynamicInfoService
                    .getDynamicInfoList(subject.getId(),APP_KEY,page, pageSize);
            return list;
        }
    }

    @GetMapping("/detail/{dynamicId}")
    public Object getDynamicInfo(HttpServletRequest request,Authentication token,
                                 @PathVariable("dynamicId") long dynamicId){

        Subject subject = (Subject) token.getPrincipal();
        Boolean isAudit = getAudit(request);
        if(!isAudit) {
            return dynamicInfoService.getDynamicInfoById(dynamicId, subject.getId());
        }else{
            return whitePacketDynamicInfoService.getDynamicInfoById(dynamicId,subject.getId());
        }
    }


    @PostMapping("/like")
    public Object addUserVideoLove(HttpServletRequest request,Authentication token,long  dynamicId) {
        Subject subject = (Subject) token.getPrincipal();
        Long userId = subject.getId();
        Boolean isAudit = getAudit(request);
        if(!isAudit){
            return dynamicInfoService.clickDynamicLike(userId,dynamicId);
        }else{
            return whitePacketDynamicInfoService.clickDynamicLike(userId,dynamicId);
        }


    }


    /**
     * 赠送礼物
     */
    @PostMapping("/gift")
    public void saveGiftSpend(Authentication token, @Validated(GiftSpendCheck.class) DynamicGiftInfoDTO dynamicGiftInfoDTO,
                              HttpServletRequest request) {

        Subject subject = (Subject) token.getPrincipal();

        Boolean isAudit = getAudit(request);
        if(!isAudit){
            DynamicDetailInfoVo dynamicDetailInfoVo = dynamicInfoService
                    .getDynamicInfoByDynamicId(dynamicGiftInfoDTO.getDynamicId());

            if(dynamicDetailInfoVo!=null){

                dynamicGiftInfoDTO.setOutUserId(Integer.parseInt(subject.getId()+""));

                dynamicGiftInfoDTO.setInUserId(Integer.parseInt(dynamicDetailInfoVo.getUserId()+""));

                GiftSpend entity = new GiftSpend();

                BeanUtils.copyProperties(dynamicGiftInfoDTO,entity);

                giftSpendService.saveGiftSpend(entity);

                dynamicInfoService.saveDynamicGiftInfo(entity,dynamicGiftInfoDTO.getDynamicId());
            }
        }else{
            WhitePacketDynamicDetailInfoVo dynamicDetailInfoVo = whitePacketDynamicInfoService
                    .getDynamicInfoByDynamicId(dynamicGiftInfoDTO.getDynamicId());
            if(dynamicDetailInfoVo!=null){

                GiftSpend entity = new GiftSpend();

                dynamicGiftInfoDTO.setInUserId(Integer.parseInt(dynamicDetailInfoVo.getUserId()+""));

                dynamicGiftInfoDTO.setOutUserId(Integer.parseInt(subject.getId()+""));



                BeanUtils.copyProperties(dynamicGiftInfoDTO,entity);

                giftSpendService.saveGiftSpend(entity);


                whitePacketDynamicInfoService.saveDynamicGiftInfo(entity,dynamicGiftInfoDTO.getDynamicId());
            }
        }


    }


    @GetMapping("/{userId}/{page}-{pageSize}")
    public Object getUserDynamicInfoList(HttpServletRequest request,Authentication token, @PathVariable("userId") Long userId,
                                                      @PathVariable("page") Integer page,
                                                      @PathVariable("pageSize") Integer pageSize) {
        if(userId == null || userId ==0){
            throw new ConsumeRuntimeException("用户id不正确");
        }
        if (pageSize <= 0) {
            pageSize = 20;
        }

        if (page <= 0) {
            page = 1;
        }

        Subject subject = (Subject) token.getPrincipal();

        Boolean isAudit = getAudit(request);
        if(!isAudit){
            List<DynamicInfoVo> list = dynamicInfoService.getDynamicInfoListByUserId(subject.getId(),userId,page, pageSize);
            return list;
        }else{
            List<WhitePacketDynamicInfoVo> list = whitePacketDynamicInfoService.getDynamicInfoListByUserId(APP_KEY,
                    subject.getId(), userId,page, pageSize);
            return list;
        }



    }

    /**
     * 分享
     */
    @PostMapping("/share")
    public void setShare(HttpServletRequest request,Long dynamicId){
        Boolean isAudit = getAudit(request);
        if(!isAudit) {
            dynamicInfoService.setShareInfo(dynamicId);
        }else{
            whitePacketDynamicInfoService.setShareInfo(dynamicId);
        }
    }

    @GetMapping("/share/{dynamicId}")
    public Object getShareByDynamicId(HttpServletRequest request,@PathVariable("dynamicId") Long dynamicId){
        if(dynamicId == null || dynamicId ==0){
            throw new ConsumeRuntimeException("动态id不正确");
        }
        Boolean isAudit = getAudit(request);
        if(!isAudit){
            Map<String,Object> obj = dynamicInfoService.getShareDynamicInfoByDynamicId(dynamicId);
            return obj;
        }else{
            Map<String,Object> obj = whitePacketDynamicInfoService.getShareDynamicInfoByDynamicId(dynamicId*-1);
            return obj;
        }
    }

    /**
     * 如何动态id为负数，代表使用白包数据
     * @param dynamicId
     * @return
     */
    @GetMapping("/share/textContent/{dynamicId}")
    public Object getShareTextByDynamicId(@PathVariable("dynamicId") Long dynamicId){
        if(dynamicId>0){
            return dynamicInfoService.getShareTextDynamicInfoByDynamicId(dynamicId);
        }else{
            return whitePacketDynamicInfoService.getShareTextDynamicInfoByDynamicId(Math.abs(dynamicId));
        }

    }

    @PostMapping("/report")
    public void setReport(HttpServletRequest request,Authentication token, @Validated DynamicReportInfoDTO obj,
                          BindingResult bindingResult){
        Subject subject = (Subject) token.getPrincipal();
        obj.setUserId(subject.getId());
        if(bindingResult.hasErrors()){
            throw  new ConsumeRuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }
        Boolean isAudit = getAudit(request);
        if(!isAudit) {
            dynamicInfoService.setReport(obj);
        }
    }


    @GetMapping("/follow/{page}-{pageSize}")
    public Object getFollowDynamicInfoList(HttpServletRequest request,Authentication token,
                                                      @PathVariable("page") Integer page,
                                                      @PathVariable("pageSize") Integer pageSize) {

        Subject subject = (Subject) token.getPrincipal();

        if (pageSize <= 0) {
            pageSize = 20;
        }

        if (page <= 0) {
            page = 1;
        }

        boolean isAudit = getAudit(request);
        if(!isAudit) {
            List<DynamicInfoVo> list = dynamicInfoService.getFollowDynamicInfoListByUserId(subject.getId(), page, pageSize);
            return list;
        }else{
            List<WhitePacketDynamicInfoVo> list = whitePacketDynamicInfoService
                    .getFollowDynamicInfoListByUserId(APP_KEY,subject.getId(), page, pageSize);
            return list;
        }
    }


    /**
     * 获取审核状态
     * @param request
     * @return
     */
    private Boolean getAudit(HttpServletRequest request) {
        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);
        OpenApiStatus ops = openApiService.getOpenApi(commonHead);
        if(ops != null && ops.getForwardAudit() && ops.getBackAudit()){
            return true;
        }else{
            return false;
        }
    }

}
